package com.arsn.myf.business.service.impl;

import com.arsn.myf.common.util.auth.AuthUtil;
import com.arsn.myf.business.entity.Leave;
import com.arsn.myf.business.mapper.LeaveMapper;
import com.arsn.myf.business.service.LeaveService;
import com.arsn.myf.business.vo.LeaveVO;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.flowable.engine.IdentityService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 请假申请接口服务实现层
 * @author zhongrj
 * @since 2022-11-04
 */
@Service
public class LeaveServiceImpl extends ServiceImpl<LeaveMapper,Leave> implements LeaveService {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private TaskService taskService;

    /**
     * 查询请假的分页数据
     * @param page
     * @param leave
     * @return
     */
    @Override
    public IPage<LeaveVO> selectLeavePage(Page<LeaveVO> page, LeaveVO leave) {
        List<LeaveVO> leaveVOList = baseMapper.selectLeavePage(page, leave);
        //返回
        return page.setRecords(leaveVOList);
    }

    /**
     * 查询详情
     * @param leave
     * @return
     */
    @Override
    public LeaveVO getLeaveDetail(LeaveVO leave) {
        return baseMapper.getLeaveDetail(leave);
    }

    /**
     * 请假流程发起
     * @param leave 请假对象信息
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean startLeaveTask(LeaveVO leave) {
        boolean flag = false;
        //设置
        Long userId = AuthUtil.getUserId();
        leave.setCreateUser(userId);
        leave.setUpdateUser(userId);
        leave.setCreateTime(new Date());
        leave.setUpdateTime(new Date());

        //保存数据
        flag = this.save(leave);
        //数据保存成功
        if (flag) {
            //设置流程发起人,该操作会将SecurityContextHolder.getContext().getAuthentication().getPrincipal 修改為 UserIdPrincipal
            identityService.setAuthenticatedUserId(userId.toString());
            //参数设置
            Map<String, Object> map = new HashMap<>();
            //计算天数
            long day = calculateNumberDays(leave.getStartTime(), leave.getEndTime());
            //设置参数
            map.put("applyUser", leave.getTaskUser());
            map.put("day", day);
            map.put("createUser", AuthUtil.getUsername());
            //任务启动
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("my_leave", map);
            if (null != processInstance) {
                //更新请假信息
                leave.setProcessInstanceId(processInstance.getId());
                leave.setProcessDefinitionId(processInstance.getProcessDefinitionId());
                //更新
                flag = updateById(leave);
            }
        }
        //返回
        return flag;
    }

    /**
     * 计算天数
     * @param startTime
     * @param endTime
     * @return
     */
    private long calculateNumberDays(Date startTime, Date endTime) {
        return Duration.between(startTime.toInstant(), endTime.toInstant()).toDays();
    }
}
